<?php
    /**
     * Created by PhpStorm.
     * User: mybook-lhp
     * Date: 18/8/23
     * Time: 上午9:38
     */

    namespace app\member\api;


    use app\common\controller\API;
    use app\common\utils\UtilAuthByRedis;
    use app\common\utils\UtilEncryption;
    use app\common\utils\UtilJwt;
    use app\member\logic\Member;
    use app\member\model\MemberInfoModel;
    use app\member\model\MemberModel;
    use think\Cache;

    class Auth extends API
    {

        /**
         * 登陆
         * api GET /member/auth/login
         *
         * @no_auth
         *
         * @param  int    $phone    手机号码
         * @param  string $password 登陆密码
         *
         * @return array $code  200成功并返回token500失败
         * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
         * @throws \think\Exception
         * @throws \think\db\exception\DataNotFoundException
         * @throws \think\db\exception\ModelNotFoundException
         * @throws \think\exception\DbException
         */
        public function login()
        {

            $data = $this->request->param();
            // 验证
            $this->check_validate($data, 'Auth.login');
            $data = $data;

            $phone = $data['phone'];
            $pwd = $data['password'];
            $pwd = UtilEncryption::encryptMd5($pwd, config('member_pwd_key'));

            $member_info = MemberModel::field('id,phone,password,status')->where(['phone' => $phone, 'password' => $pwd])->find();

            if ($member_info) {
                if ($member_info['status'] == 0) {
                    $this->error('账号已冻结，请联系客服！');
                }
                $member = MemberInfoModel::getMemberInfo($member_info['id']);
                $nowtime = time();
                $member['token'] = UtilJwt::encode(['member_id' => $member_info->id, 'phone' => $member_info->phone, 'create_time' => $nowtime, 'end_datetime' => $nowtime + (config('JwtRuntime') * 86400), 'sn' => UtilEncryption::UniqueID(),], config('JwtKey'));

                //                $Redis = UtilAuthByRedis::getInstance(config('redis'));
                //                $Redis->setToken('member_id_' . $member_info->id,$member['token']);
                $this->success('登陆成功！', '', $member);
            } else {
                $this->error('用户不存在或密码错误！');
            }
        }

        /**
         * 刷新token
         * api POST /member/auth/refresh_token
         *
         * @throws \think\Exception
         */
        public function refresh_token()
        {

            $nowtime = time();
            $JwtRuntime = (config('JwtRuntime') * 86400);//Token有效时间
            $Redis = UtilAuthByRedis::getInstance(config('redis'));
            $Redis->setToken(HTTP_X_AUTH_TOKEN['sn'], $_SERVER['HTTP_X_AUTH_TOKEN']);
            $jwt = HTTP_X_AUTH_TOKEN;
            $jwt['end_datetime'] = $nowtime + $JwtRuntime;
            $jwt['sn'] = UtilEncryption::UniqueID();
            $Token = UtilJwt::encode($jwt, config('JwtKey'));
            $this->result(['token' => $Token]);
        }

        /**
         * 测试token 方便用于调试
         *
         * @throws \think\Exception
         * @throws \think\db\exception\DataNotFoundException
         * @throws \think\db\exception\ModelNotFoundException
         * @throws \think\exception\DbException
         */
        protected function debuglogin()
        {

            $phone = $this->request->param('phone');
            $password = $this->request->param('password');

            if ($password !== 'qqqqqq') $this->error('缺少参数');
            $member_info = MemberModel::field('phone')->where(['phone' => $phone])->find();
            if ($member_info) {
                if ($member_info['status'] == 0) {
                    $this->error('账号已冻结，请联系客服！');
                }
                $member = MemberInfoModel::getMemberInfo($member_info['id']);
                $nowtime = time();
                $member['token'] = UtilJwt::encode(['member_id' => $member_info->id, 'phone' => $member_info->phone, 'create_time' => $nowtime, 'end_datetime' => $nowtime + (config('JwtRuntime') * 86400), 'sn' => UtilEncryption::UniqueID(),], config('JwtKey'));
                $this->success('登陆成功！', '', $member);
            } else {
                $this->error('用户不存在或密码错误！');
            }

        }

        /**
         * 获取手机验证码(验证手机号是否存在)
         * api GET /member/auth/get_pwd_code
         *
         * @no_auth
         *
         * @param int phone 手机号码
         *
         * @return array data 返回值
         * @throws \think\db\exception\DataNotFoundException
         * @throws \think\db\exception\ModelNotFoundException
         * @throws \think\exception\DbException
         */
        public function get_pwd_code()
        {

            $data = $this->request->param(); //手持身份证
            $data['member_id'] = env('member_id');;
            // 验证
            $this->check_validate($data, 'Auth.get_pwd_code');

            $res = Member::sendPhoneCode($data);
            if ($res['type' == 'success']) {
                $this->success($res['msg']);
            } else {
                $this->error($res['msg']);
            }

        }

        /**
         * 获取手机验证码（注册）
         * api GET /member/auth/push_phone_code
         *
         * @no_auth
         *
         * @param int phone 手机号码
         *
         * @return array data 返回值
         * @throws \think\db\exception\DataNotFoundException
         * @throws \think\db\exception\ModelNotFoundException
         * @throws \think\exception        \DbException
         */
        public function push_phone_code()
        {

            $data = $this->request->param(); //获取参数
            // 验证
            $this->check_validate($data, 'Auth.push_phone_code');

            $res = Member::sendPhoneCode($data);
            if ($res['type'] == 'success') {
                $this->success($res['msg']);
            } else {
                $this->error($res['msg']);

            }
        }

        /**
         * 用户注册
         * api GET /member/auth/register
         *
         * @no_auth
         *
         * @param int $phone          手机号码
         * @param int $password       登陆密码
         * @param int $re_password    确认登陆密码
         * @param int $validate_code  验证码
         * @param int $referrer_phone 推荐人手机号没有则不提交这个字段
         *
         * @return array code 200成功500错误
         * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
         */
        public function register()
        {

            $data['type'] = '';
            $data = $this->request->param(); //获取参数
            // 验证
            $this->check_validate($data, 'Auth.register');
            //当验证码正确时
            if (Cache::get('timephone_' . $data['phone']) == $data['validate_code']) {
                //注册用户
                //                $referrer_phone = isset($data['referrer_phone']) ? $data['referrer_phone'] : false; //介绍人
                $referrer_phone = false; //介绍人
                $reqst = Member::app_register($data['phone'], $data['password'], $referrer_phone);
                if (isset($reqst['success'])) {
                    $this->success($reqst['success']);
                } else {
                    $this->error($reqst['error']);
                }
            } else {
                $this->error('验证码不正确，或已过期，请重新输入！');
            }
        }

        /**
         * 用户注册(推广)
         * api GET /member/auth/register
         *
         * @param int $phone          手机号码
         * @param int $password       登陆密码
         * @param int $re_password    确认登陆密码
         * @param int $validate_code  验证码
         * @param int $referrer_phone 推荐人手机号没有则不提交这个字段
         *
         * @return array code 200成功500错误
         * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
         */
        public function register_r()
        {

            $data['type'] = '';
            $data = $this->request->param(); //获取参数
            // 验证
            $this->check_validate($data, 'Auth.register');

            //注册用户

            $referrer_phone = isset($data['referrer_phone']) ? $data['referrer_phone'] : false; //介绍人


            //当验证码正确时
            if (Cache::get('timephone_' . $data['phone']) == $data['validate_code']) {
                $reqst = Member::app_register($data['phone'], $data['password'], $referrer_phone, $data);
                if (isset($reqst['success'])) {
                    $this->success($reqst['success']);
                } else {
                    $this->error($reqst['error']);
                }

            } else {
                $this->error('验证码不正确，或已过期，请重新输入！');
            }
        }

        /**
         * 找回密码
         * api GET /member/auth/forget_pwd
         *
         * @no_auth
         *
         * @param int phone 手机号码
         * @param int password 登陆密码
         * @param int re_password 确认登陆密码
         * @param int validate_code 验证码
         *
         * @return array data 返回值
         */
        public function forget_pwd()
        {

            $data = $this->request->param();
            // 验证
            $this->check_validate($data, 'Auth.forget_pwd');

            //当验证码正确时
            if (Cache::get('timephone_' . $data['phone']) == $data['validate_code']) {
                $result = Member::reset_password($data['phone'], $data['password']);
                if (isset($result)) {
                    $this->success('修改成功!');
                } else {
                    $this->error('修改失败！');
                }

            } else {
                $this->error('验证码不正确，或已过期，请重新输入！');
            }

        }
    }